import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Scrollbar from 'react-smooth-scrollbar'
import Dropzone from 'react-dropzone'
import DatePicker from 'react-datepicker'
import moment from 'utils/moment'
import md5 from 'js-md5'
import arrow from 'images/index/picture/arrow.png'
import 'react-datepicker/dist/react-datepicker.css'
import { confirmAlert } from 'react-confirm-alert' // Import
import 'react-confirm-alert/src/react-confirm-alert.css' // Import css
import {
  farmLandLogSave,
  farmLandLogDelete,
  findlandLogList,
  deleteLogPhotoById,
  findLogVideoById,
  deleteLogVideoById
} from 'utils/Api'
import { destroyDragDrop } from '_redux/actions/dragDrops'
import VideoItem from './VideoItem'

import add from 'images/index/picture/+_.png'

import { connect } from 'react-redux'
import { updateLists } from '_redux/actions/picture.js'

class AddVideoLogger extends Component {
  constructor() {
    super()
    this.state = {
      files: [],
      videos: [],
      startDate: moment(),
      content: '',
      submiting: false,
      list: [],
      videoList: [],
      describe: {},
      idDescribe: {},
      showLoggerImg: false,
      type: '0',
      progress: 0
    }
  }
  componentDidMount() {
    const { picture: { logger } } = this.props
    if (!logger) {
      this.setState({
        files: [],
        videos: [],
        startDate: moment(),
        content: '',
        submiting: false,
        list: [],
        videoList: [],
        describe: {},
        idDescribe: {},
        showLoggerImg: false,
        type: '0',
        progress: 0
      })
      return
    }
    this.getInfo(logger)
  }
  getInfo = (logger) => {
    const fd = new FormData()
    fd.append('pageNo', '1')
    fd.append('pageSize', '-1')
    fd.append('logId', logger.id)
    findLogVideoById(fd)
      .then(({ msg, result: { list } }) => {
        if (msg === '200') {
          const { picture: { logger: logger2 } } = this.props
          if (list) {
            this.setState({
              type: '1',
              videoList: list,
              startDate: moment(logger2.date),
              content: logger2.content
            })
          } else {
            this.setState({
              type: '1',
              videoList: [],
              startDate: moment(logger2.date),
              content: logger2.content
            })
          }
        }
      })
  }
  UNSAFE_componentWillUpdate(nextProps, nextState) {
    const length = this.state.files.length + this.state.list.length
    const nextLen = nextState.files.length + nextState.list.length
    if (length !== nextLen) {

    }
  }
  //组件将被卸载  
  componentWillUnmount() {
    //重写组件的setState方法，直接返回空
    this.setState = (state, callback) => {
      return
    }
  }
  componentDidUpdate(prevProps, prevState) {
    const { picture: { logger } } = this.props
    if (!logger) {
      return
    }
    if (!prevProps.logger) {
      return
    }
    if (prevProps.logger.id !== logger.id) {
      this.getInfo(logger)
    }
  }
  handleChange = (date) => {
    this.setState({
      startDate: date
    })
  }
  contentChange = (e) => {
    this.setState({
      content: e.target.value
    })
  }
  describe = (obj) => {
    const { describe, idDescribe } = this.state
    if (obj.idDescribe) {
      idDescribe[obj.id] = obj.content
    } else {
      describe[obj.name] = obj.content
    }
    this.setState({
      describe,
      idDescribe
    })
  }
  upload = () => {
    const { picture: { logger }, feature: { feature } } = this.props
    const id = feature.getId().replace('tb_farmland.', '')
    const seasonId = feature.get('season_id')
    const fd = new FormData()

    fd.append('farmlandLogStr', JSON.stringify({
      seasonId,
      landId: id,
      date: this.state.startDate.format('YYYY-MM-DD'),
      content: this.state.content,
      id: logger && logger.id,
      type: '1',
    }))
    // type
    this.state.videos.map(video => fd.append('video', video))
    const { describe, idDescribe } = this.state
    const describeStr = []
    Object.keys(describe).map(key => {
      describeStr.push({
        key,
        value: describe[key]
      })
    })
    describeStr.length !== 0 && fd.append('describeStr', JSON.stringify(describeStr))

    const idDescribeKvsStr = []
    Object.keys(idDescribe).map(key => {
      idDescribeKvsStr.push({
        key,
        value: idDescribe[key]
      })
    })
    const config = {
      onUploadProgress: progressEvent => {
        const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
        this.setState({
          progress: complete
        })
      },
      headers: {
        'Content-Type': 'multipart/form-data'
      },
    }
    idDescribeKvsStr.length !== 0 && fd.append('idDescribeKvsStr', JSON.stringify(idDescribeKvsStr))
    return farmLandLogSave(fd, config)
      .then(({ msg }) => {
        if (msg === '200') {
          this.successCallback()
          this.updateLists()
        }
        this.setState({
          submiting: false
        })
      })
  }

  submit = (e) => {
    e.preventDefault()
    this.setState({
      submiting: true
    })
    this.upload()
  }
  updateLists = () => {
    const { feature } = this.props.feature
    const id = feature.getId().replace('tb_farmland.', '')
    const seasonId = feature.get('season_id')
    const fd = new FormData()
    fd.append('pageNo', 1)
    fd.append('pageSize', -1)
    fd.append('landId', id)
    fd.append('seasonId', seasonId)
    findlandLogList(fd)
      .then(({ msg, result: { list = [] } }) => {
        if (msg === '200') {
          this.props.updateLists(list)
        }
      })
  }
  successCallback() {
    const { picture: { logger } } = this.props
    if (logger && logger.id) {
      confirmAlert({
        // title: 'Confirm to submit',
        message: '修改成功',
        buttons: [
          {
            label: '退出',
            onClick: () => this.props.destroyDragDrop('editVideoLogger')
          }
        ]
      })
      return
    }
    confirmAlert({
      message: '日志已创建，是否继续添加？',
      buttons: [
        {
          label: '是',
          onClick: () => {
            this.setState({

              videos: [],
              content: '',
              submiting: false,
              list: [],
              videoList: [],
              describe: {},
              idDescribe: {},
              showLoggerImg: false,
              progress: 0
            })
          }
        },
        {
          label: '否',
          onClick: () => this.props.destroyDragDrop('addVideoLogger')
        }
      ]
    })
  }
  onDrop = (files, rejectFiles) => {
    if (rejectFiles.length > 1) {
      alert('上传文件错误，请重新上传')
      return
    }
    files.map((file, i) => {
      file.md5 = md5((Date.now() + i).toString())
    })

    this.setState({
      files: [
        ...this.state.files,
        ...files
      ]
    })
  }

  onVideoDrop = (videos, rejectFiles) => {
    if (rejectFiles.length >= 1) {
      alert('上传文件错误(大小不能大于30M)，请重新上传')
      return
    }
    if (this.state.videos.length === 1) {
      alert('视频一次只能上传一个')
      return
    }
    videos.map((video, i) => {
      video.md5 = md5((Date.now() + i).toString())
    })

    this.setState({
      videos: [
        ...this.state.videos,
        ...videos
      ]
    })
  }
  deleteFileByIndex = (e) => {
    e.preventDefault()
    const md5 = e.target.getAttribute('data-index')
    this.setState({
      files: this.state.files.filter(file => file.md5 !== md5)
    })
  }
  deleteVideoById = (e) => {
    e.preventDefault()
    const md5 = e.target.getAttribute('data-index')
    this.setState({
      videos: this.state.videos.filter(file => file.md5 !== md5)
    })
  }
  deletelistById = (e) => {

    e.preventDefault()
    const id = e.target.getAttribute('data-index')
    const fd = new FormData()
    fd.append('id', id)
    deleteLogPhotoById(fd)
      .then(({ msg }) => {
        if (msg === '200') {
          const { list } = this.state
          this.setState({
            list: list.filter(list => list.id !== id)
          })
          this.updateLists()
        }
      })
  }

  deleteVideoListById = (e) => {
    e.preventDefault()
    const id = e.target.getAttribute('data-index')
    const fd = new FormData()
    fd.append('id', id)
    deleteLogVideoById(fd)
      .then(({ msg }) => {
        if (msg === '200') {
          const { videoList } = this.state
          this.setState({
            videoList: videoList.filter(list => list.id !== id)
          })
          this.updateLists()
        }
      })


  }
  showLoggerImg = () => {
    this.setState({
      showLoggerImg: !this.state.showLoggerImg
    })
  }
  deleteLandLog = (e) => {
    const { picture: { logger } } = this.props
    e.preventDefault()
    confirmAlert({
      message: '确认删除？',
      buttons: [
        {
          label: '确认',
          onClick: () => {
            this.delete(logger.id)
            this.props.destroyDragDrop('editVideoLogger')
          }
        },
        {
          label: '取消',
          onClick: () => { }
        }
      ]
    })

  }
  delete = (logId) => {
    const fd = new FormData()
    fd.append('logId', logId)
    farmLandLogDelete(fd)
      .then(({ msg }) => {
        if (msg === '200') {
          this.updateLists()
        }
      })
  }
  switchChange = (type) => {
    this.setState({
      type: type ? '1' : '0'
    })
  }
  render() {
    const { picture: { logger } } = this.props
    return (
      <div className='add-video-logger' >
        <form onSubmit={this.submit}>
          <div className='log-str'>
            <div className='input-group'>
              <label htmlFor="date">日期：</label>
              <DatePicker
                dateFormat="YYYY-MM-DD"
                selected={this.state.startDate}
                onSelect={this.handleChange}
              />
            </div>
            <div className='input-group'>
              <label htmlFor="logger"> 日志：</label>
              <textarea name="logger" id="logger"
                value={this.state.content}
                onChange={this.contentChange} />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', fontSize: '13px', padding: '0 15px', cursor: 'pointer' }} onClick={this.showLoggerImg}>
            <img src={arrow} />
            添加视频
            <div style={{ borderBottom: '1px solid #ddd', flexGrow: 1 }}></div>
          </div>
          <Scrollbar>
            <div className='logger-video' style={{ display: this.state.showLoggerImg ? 'flex' : 'none' }}>
              {/* 本地上传列表 */}
              {
                this.state.videos.map(video => <VideoItem
                  key={video.md5}
                  id={video.md5}
                  video={video}
                  url={video.preview}
                  delete={this.deleteVideoById}
                  describe={this.describe}
                />)
              }
              {/* 从服务器获得列表 */}
              {
                this.state.videoList.map(video => <VideoItem
                  key={video.id}
                  video={video}
                  id={video.id}
                  url={video.path}
                  delete={this.deleteVideoListById}
                  describe={this.describe} />)
              }

              <div className='logger-box'>
                <Dropzone className='drop-zone'
                  accept="video/mp4"
                  maxSize={31457280}
                  onDrop={this.onVideoDrop}
                  multiple={false}>
                  <img src={add} alt="" />
                  <label>添加视频</label>
                </Dropzone>
              </div>
            </div>
          </Scrollbar>
          <div className='submit'>
            <div>
              <input type="submit" value={this.state.submiting ? '保存中...' : '保存'} disabled={this.state.submiting} />
              {this.state.submiting &&
                (this.state.progress < 100 ? `视频正在上传${this.state.progress}%` : '上传完成，正在处理，请耐心等待')}
            </div>
            {/* <input type="submit" value={'删除'}/> */}
            {logger &&
              logger.id &&
              <a href='#' className='delete' onClick={this.deleteLandLog}>删除</a>}
          </div>
        </form>

      </div>)
  }
}
AddVideoLogger.propTypes = {
  feature: PropTypes.object,
  destroyDragDrop: PropTypes.func,
  updateLists: PropTypes.func,
  log: PropTypes.object,
  logger: PropTypes.object,
  delete: PropTypes.func,
  width: PropTypes.string,
  picture: PropTypes.object,
}
const mapStateToProps = function (state) {
  return {
    picture: state.picture,
    feature: state.feature,
  }
}
const mapDispatchToProps = function (dispatch) {
  return {
    updateLists: (show) => dispatch(updateLists(show)),
    destroyDragDrop: id => dispatch(destroyDragDrop(id))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(AddVideoLogger)